package com.eascs.admin.o2o.loan.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.eascs.admin.o2o.detail.service.OaLoanapplyDetailService;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.action.O2oSearchCustemer;
import com.eascs.admin.o2o.loan.entity.BCRecommendationEntity;
import com.eascs.admin.o2o.loan.entity.BCRecommendationUpdateRecord;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.entity.O2oSDEntity;
import com.eascs.admin.o2o.loan.form.LoanUserForm;
import com.eascs.admin.o2o.loan.service.BCRecommendationService;
import com.eascs.admin.o2o.loan.service.O2oEmployeeService;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.loan.service.O2oSdService;
import com.eascs.admin.o2o.loan.trans.O2oLoanUserTransFormart;
import com.eascs.admin.o2o.loan.utils.AESUtil;
import com.eascs.admin.o2o.o2ozx.serviceimpl.O2oLoadUserZxServiceImpl;
import com.eascs.admin.o2o.o2ozx.serviceimpl.O2oZxServiceImpl;
import com.eascs.admin.o2o.zx.entity.O2oLoanUserEntityZx;
import com.eascs.admin.o2o.zx.entity.O2oZxEntity;
import com.eascs.admin.recordlog.constant.O2oLogType;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.brand.service.O2oPartnerService;
import com.eascs.common.doc.word.WordPOIUntil;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.StringUtil;
import com.eascs.crm.common.custnew.entity.CustomerEntity;
import com.eascs.crm.common.custnew.service.CustomerService;
import com.eascs.crm.common.entity.CustomerBasicInfoEntity;
import com.eascs.crm.common.entity.CustomerShopInfoEntity;
import com.eascs.crm.common.service.ICustomerInfoService;
import com.eascs.crm.common.service.TdService;
import com.eascs.crm.common.vo.CustomerView;
import com.eascs.crm.common.vo.QueryCustomerVO;
import com.eascs.datalist.entity.O2oDataListEntity;
import com.eascs.datalist.service.O2oDataListService;
import com.eascs.file.FileService;
import com.eascs.file.FileTypeConstants;
import com.eascs.gaczcontract.entity.CustomerBasicInfo;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.PaginationRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.site.view.button.ShowButtonFilter;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.service.sys.SysPermissionService;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;

@RestController
@RequestMapping("/loanrest")
public class O2oLoanUserRestController extends BaseRestController {

	private static Logger log = LoggerFactory.getLogger(O2oLoanUserRestController.class);
	@Autowired
	private O2oLoanUserService loanService;
	@Autowired
	O2oZxServiceImpl o2oZxServiceImpl;
	@Autowired
	O2oLoadUserZxServiceImpl o2oLoadUserZxServiceImpl;
	@Autowired
	private O2oDataListService o2oDataListService;

	@Reference
	private WorkFlowService workFlowService;

	@Reference
	private TdService tdService;

	@Reference
	private SysPermissionService sysPermissionService;

	@Reference
	private SysOrgService sysOrgService;

	@Reference
	ICustomerInfoService iCustomerInfoService;

	@Autowired
	private FileService fileService;

	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;

	@Autowired
	private O2oEmployeeService o2oEmployeeService;

	@Autowired
	private BCRecommendationService bcRecommendationService;

	@Autowired
	private O2oSdService o2oSdService;

	@Autowired
	O2oPartnerService partnerService;

	@Reference
	CustomerService customerService;

	@Value("${o2o.admin.roleCode}")
	private String roleCode;

	@Value("${o2o.admin.customerLXUrl}")
	String customerLXUrl;

	@Value("${o2o.admin.addUserUrl}")
	String crmaddUrl;

	@Value("${web.homeUrl}")
	String serviceHomeUrl;
	@Value("${web.crm.url}")
	String crmHomeUrl;

	@Value("${o2o.admin.crm}")
	String crmUrl;

	@Autowired
	private O2oLoanUserService o2oLoanUserService;

	@Autowired
	private OaLoanapplyDetailService oaLoanapplyDetailService;

	@RequestMapping(value = "query")
	public String index(LoanUserForm loanUserForm) {
		PageResult<Object[]> pageResult = new PageResult<>(10, 0, 10);
		String url = "/loanUser/find?pageIndex=";
		pageResult = loanService.findByPage(pageResult.getPageSize(), pageResult.getPageIndex(), loanUserForm);
		String titles[] = {};
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, url);
		paginationInfo.setBuildPagingNavigation(true);

		ViewContext.put("paginationInfo", paginationInfo);

		return "loanManagement/loantotla";
	}

	/**
	 * 删除附件
	 * 
	 * @param datalistno
	 * @return
	 */
	@RequestMapping(value = "/delete/{datalistno}")
	public BaseRestResult<String> deleteFile(@PathVariable("datalistno") String datalistno) {
		O2oDataListEntity o2oDataList = fileService.getByidDataList(datalistno);
		o2oDataList.setIsDelete(StatusContexts.O2O_YES);
		if (fileService.updateEntityById(o2oDataList) > 0) {
			insertLog(O2oLogType.FILE_STATUS_D, "删除，上传附件,ID:" + datalistno);
			return BaseRestResult.buildClosestReloadResult();
		} else {
			return BaseRestResult.warn("删除失败").andRefresh();
		}
	}

	/**
	 * 删除其他附件
	 * 
	 * @param datalistno
	 * @return
	 */
	@RequestMapping(value = "/deleteOth/{datalistno}")
	public BaseRestResult<String> deleteOthFile(@PathVariable("datalistno") String datalistno) {
		O2oDataListEntity o2oDataList = fileService.getByidDataList(datalistno);
		o2oDataList.setIsDelete(StatusContexts.O2O_YES);
		if (fileService.updateEntityById(o2oDataList) > 0) {
			insertLog(O2oLogType.FILE_STATUS_D, "删除，上传其他附件,ID:" + datalistno);
			return BaseRestResult.buildClosestReloadResult();
		} else {
			return BaseRestResult.warn("删除失败").andRefresh();
		}
	}

	/**
	 * 附件上传 局部刷新DIV
	 * 
	 * @param loanapplyNo
	 * @param massege
	 * @return
	 */
	@RequestMapping(value = "/findloan")
	public HtmlRestResult loanDetail(String loanapplyNo, String massege) {
		O2oLoanapplyEntity o2oLoanapplyEntity = o2oLoanapplyService.findById(loanapplyNo);
		/**** 查询附件 ****/
		List<O2oDataListEntity> o2oDataList = o2oDataListService.findByEntityList(loanapplyNo);
		O2oLoanUserEntity customer = o2oLoanUserService.findById(o2oLoanapplyEntity.getLoanId(), loanapplyNo);
		O2oLoanUserEntity customerMate = o2oLoanUserService.findSpouseId(o2oLoanapplyEntity.getLoanId(), loanapplyNo);
		if (customerMate != null) {
			if (customer != null && customerMate != null) {
				/*
				 * QueryCustomerVO vo2 = new QueryCustomerVO();
				 * vo2.setCustomer_id(customer.getBasicInfo().getMateId());
				 * CustomerView customer1 =
				 * iCustomerInfoService.geCustomerView(vo2);
				 */
				ViewContext.put("materBasic", customerMate);
			}
		}

		ViewContext.put("o2oDataList", o2oDataList);
		ViewContext.put("errorMassege", massege);
		ViewContext.put("loanApplyFileEntity", o2oLoanapplyEntity);
		return new HtmlRestResult("loanManagement/loanfileDiv");
	}

	/**
	 * 担保人附件上传dev
	 * 
	 * @param loanapplyNo
	 * @param massege
	 * @return
	 */
	@RequestMapping(value = "/sponsorfindloan")
	public HtmlRestResult sponsorDetail(String loanapplyNo, String massege, String sponsorId) {
		O2oLoanapplyEntity o2oLoanapplyEntity = o2oLoanapplyService.findById(loanapplyNo);
		/**** 查询附件 ****/
		// 贷款id，还有担保人id
		List<O2oDataListEntity> o2oDataList = o2oDataListService.findByEntityList(loanapplyNo, sponsorId);

		/*
		 * QueryCustomerVO vo = new QueryCustomerVO();
		 * vo.setCustomer_id(sponsorId); CustomerView sponsor =
		 * iCustomerInfoService.geCustomerView(vo);
		 */

		O2oLoanUserEntity o2oSponsor = o2oLoanUserService.findSponsorById(sponsorId, loanapplyNo);
		// O2oLoanUserEntity customerMate =
		// o2oLoanUserService.findSpouseId(o2oLoanapplyEntity.getLoanId(),o2oLoanapplyEntity.getLoanapplyNo());

		ViewContext.put("basic", o2oSponsor);
		// ViewContext.put("expan", sponsor.getExpansionInfo());
		ViewContext.put("o2oDataList", o2oDataList);
		ViewContext.put("errorMassege", massege);
		// ViewContext.put("o2oSponsor", o2oSponsor);
		ViewContext.put("loanApplyFileEntity", o2oLoanapplyEntity);
		return new HtmlRestResult("loanManagement/sponsorfileDiv");
	}

	@RequestMapping(value = "/file")
	public BaseRestResult<String> loanUpload(@RequestParam MultipartFile file, String datalist, String loanapplyNo,
			String loanId) {
		if (datalist.equals(FileTypeConstants.DALIST_TYPE_OTH)) {
			fileService.upload(file, datalist, loanapplyNo);
			return BaseRestResult.refresh();
		}
			else {
			fileService.upload(file, datalist, loanapplyNo);
			return BaseRestResult.buildClosestReloadResult();
		}
	}

	/**
	 * 担保人附件上传
	 * 
	 * @param file
	 * @param datalist
	 * @param loanapplyNo
	 * @param loanId
	 * @param sponsorId
	 * @return
	 */
	@RequestMapping(value = "/sponsorfileupload")
	public BaseRestResult<String> sponsorloanUpload(@RequestParam MultipartFile file, String datalist,
			String loanapplyNo, String loanId, String sponsorId) {
		fileService.sponsorupload(file, datalist, loanapplyNo, sponsorId);
		return BaseRestResult.buildClosestReloadResult();
	}

	/**
	 * 上传其他附件
	 * 
	 * @param file
	 * @param datalist
	 * @param loanapplyno
	 * @param loanid
	 * @return
	 */
	@RequestMapping(value = "/othfile/{datalist}/{loanapplyno}")
	public BaseRestResult<String> othUpload(@RequestParam MultipartFile file, @PathVariable("datalist") String datalist,
			@PathVariable("loanapplyno") String loanapplyno) {
		log.info("上传其他附件开始");
		fileService.upload(file, datalist, loanapplyno);
		log.info("上传其他附件结束");
		return BaseRestResult.buildClosestReloadResult();
	}

	/**
	 * 联想回购担保方
	 * 
	 * @param o2oSearchCustemer
	 * @return
	 */
	@RequestMapping(value = "/findUnits")
	public BaseRestResult<List<Object[]>> findOAUnits(O2oSearchCustemer o2oSearchCustemer) {
		List<Object[]> data = new ArrayList<>();
		if (StringUtil.hasText(o2oSearchCustemer.getName())) {
			data = oaLoanapplyDetailService.findOAUnit(o2oSearchCustemer.getName());
		}
		return BaseRestResult.buildRestResult(data);
	}

	/**
	 * 联想经营平台
	 * 
	 * @param o2oSearchUnits
	 * @return
	 */
	@RequestMapping(value = "/search")
	public BaseRestResult<List<Object[]>> units(O2oSearchCustemer o2oSearchCustemer) {
		List<Object[]> data = new ArrayList<>();
		if (StringUtil.hasText(o2oSearchCustemer.getName())) {
			ModelResult<List<Object[]>> da = sysOrgService.getOrgListLikeName(o2oSearchCustemer.getName(),
					ActOrgEntity.ORG_LEVEL_PLATFORM, UserHolder.getUser());
			data = da.getModel();
		} else if (StringUtil.hasText(o2oSearchCustemer.getOperationName())) {
			ModelResult<List<Object[]>> da = sysOrgService.getOrgListLikeName(o2oSearchCustemer.getOperationName(),
					ActOrgEntity.ORG_LEVEL_PROVINCE_FIN_COM, UserHolder.getUser());
			data = da.getModel();
		}

		return BaseRestResult.buildRestResult(data);
	}

	/**
	 * 联想经营平台
	 * 
	 * @param o2oSearchUnits
	 * @return
	 */
	@RequestMapping(value = "/searchall")
	public BaseRestResult<List<Object[]>> unitsall(O2oSearchCustemer o2oSearchCustemer) {
		List<Object[]> data = new ArrayList<>();
		List<Integer> list = new ArrayList<Integer>();
		list.add(ActOrgEntity.ORG_LEVEL_PLATFORM);
		list.add(ActOrgEntity.ORG_LEVEL_PROVINCE_FIN_COM);
		if (StringUtil.hasText(o2oSearchCustemer.getName())) {
			ModelResult<List<Object[]>> da = sysOrgService.getOrgListLikeNameWithLevels(o2oSearchCustemer.getName(),
					list, UserHolder.getUser());
			data = da.getModel();
		}
		return BaseRestResult.buildRestResult(data);
	}
	
	/**
	 * @Description:
	 *               <p>
	 *               联想经办平台_用于中行,不要选择省区金融部
	 *               </p>
	 * @author LMX
	 * @date 2018年1月8日 下午5:56:10
	 */
	@RequestMapping(value = "/searchJB_Platform")
	public BaseRestResult<List<Object[]>> searchJB_Platform(O2oSearchCustemer o2oSearchCustemer) {
		List<Object[]> data = new ArrayList<>();
		List<Integer> list = new ArrayList<Integer>();
		list.add(ActOrgEntity.ORG_LEVEL_PLATFORM);
//		list.add(ActOrgEntity.ORG_LEVEL_PROVINCE_FIN_COM);//不要选择省区金融部
		if (StringUtil.hasText(o2oSearchCustemer.getName())) {
			ModelResult<List<Object[]>> da = sysOrgService.getOrgListLikeNameWithLevels(o2oSearchCustemer.getName(),
					list, UserHolder.getUser());
			data = da.getModel();
		}
		return BaseRestResult.buildRestResult(data);
	}

	/**
	 * 联想信贷经理
	 * 
	 * @param o2oSearchOperator
	 * @return
	 */
	@RequestMapping(value = "/operator")
	public BaseRestResult<List<Object[]>> operator(O2oSearchCustemer o2oSearchCustemer) {
		List<Object[]> data = new ArrayList<>();
		if (StringUtil.hasText(o2oSearchCustemer.getName())) {
			ModelResult<List<Object[]>> da = sysPermissionService.getOperatorList(o2oSearchCustemer.getName());
			data = da.getModel();
		}
		return BaseRestResult.buildRestResult(data);
	}

	/**
	 * 推荐人
	 * 
	 * @param o2oSearchOperator
	 * @return
	 */
	@RequestMapping(value = "/referrer")
	public BaseRestResult<List<Object[]>> referrer(O2oSearchCustemer o2oSearchCustemer) {
		List<Object[]> data = new ArrayList<>();
		data = o2oEmployeeService.getOperatorList(o2oSearchCustemer.getName());
		return BaseRestResult.buildRestResult(data);
	}

	/**
	 * 联想信贷经理--根据信贷经理联想 CODE
	 * 
	 * @param o2oSearchOperator
	 * @return
	 */
	@RequestMapping(value = "/likeOperator")
	public BaseRestResult<List<Object[]>> likeOperator(O2oSearchCustemer o2oSearchCustemer) {
		List<Object[]> data = new ArrayList<>();
		List<Integer> statusList = new ArrayList<Integer>();
		statusList.add(0);//在职
		if (StringUtil.hasText(o2oSearchCustemer.getName())) {
			ModelResult<List<Object[]>> da = sysPermissionService.getOperatorListByRoleCode(o2oSearchCustemer.getName(),
					roleCode,statusList);
			data = da.getModel();
		}
		return BaseRestResult.buildRestResult(data);
	}

	/**
	 * 联想客户名称
	 * 
	 * @param o2oSearchcustomerName
	 * @return
	 */
	@RequestMapping(value = "/customer")
	public BaseRestResult<List<Object[]>> customer(O2oSearchCustemer o2oSearchCustemer) {
		List<Object[]> data = new ArrayList<>();
		if (StringUtil.hasText(o2oSearchCustemer.getName())) {
			data = o2oLoanapplyService.getCustomerList(o2oSearchCustemer.getName());
		}
		return BaseRestResult.buildRestResult(data);
	}

	@RequestMapping(value = "/customer_province")
	public BaseRestResult<List<ActOrgEntity>> customerProvince() {
		List<ActOrgEntity> data = new ArrayList<>();
		ModelResult<List<ActOrgEntity>> da = sysOrgService.getProvinceWithUser(UserHolder.getUser().getNo());
		data = da.getModel();
		return BaseRestResult.buildRestResult(data);
	}

	/**
	 * @description 查询主申请人 贷款次数(新系统和旧系统)
	 * @description find loan count
	 * @return loan count
	 */
	@RequestMapping(value = "/find_loan_account/{loanapplyNo}/{loanId}")
	public HtmlRestResult getLoanCount(@PathVariable("loanapplyNo") String loanapplyNo,
			@PathVariable("loanId") String loanId) {
		QueryCustomerVO vo = new QueryCustomerVO();
		vo.setCustomer_id(loanId);
		log.info("=====================loanId:" + loanId.toString() + "===============loanapplyNo:" + loanapplyNo);
		CustomerView customer = iCustomerInfoService.geCustomerView(vo);
		CustomerBasicInfoEntity basicEntity = customer.getBasicInfo();
		int count = 0;
		if (basicEntity != null && basicEntity.getIdNumber() != null) {
			log.info("===================查询贷款次数人的身份证号码为：" + basicEntity.getIdNumber());
			count = o2oLoanapplyService.findLoanAccountNEW(basicEntity.getIdNumber());
		}
		log.info("=======================loan_account:" + count);
		ViewContext.put("loan_account", count);
		ViewContext.put("basic_entity", basicEntity);
		return HtmlRestResult.html("/loanManagement/loan_account");
	}

	/**
	 * @description 查询配偶 贷款次数(新系统和旧系统)
	 * @description find loan count
	 * @return loan count
	 */
	@RequestMapping(value = "/find_mater_account/{loanapplyNo}/{loanId}")
	public HtmlRestResult getMaterCount(@PathVariable("loanapplyNo") String loanapplyNo,
			@PathVariable("loanId") String loanId) {
		QueryCustomerVO vo = new QueryCustomerVO();
		vo.setCustomer_id(loanId);
		log.info("=====================loanId:" + loanId.toString() + "===============loanapplyNo:" + loanapplyNo);
		CustomerView customer = iCustomerInfoService.geCustomerView(vo);
		CustomerBasicInfoEntity basicEntity = customer.getBasicInfo();
		log.info("=======================basicEntity:" + basicEntity.toString());
		int count = 0;
		if (null != basicEntity && StringUtil.isNotBlank(basicEntity.getMateId())) {
			QueryCustomerVO vo2 = new QueryCustomerVO();
			vo2.setCustomer_id(basicEntity.getMateId());
			CustomerView customer2 = iCustomerInfoService.geCustomerView(vo2);
			CustomerBasicInfoEntity basicEntity2 = customer2.getBasicInfo();
			log.info("===================查询配偶贷款次数人的身份证号码为：" + basicEntity.getIdNumber());
			count = o2oLoanapplyService.findLoanAccountNEW(basicEntity2.getIdNumber());
			ViewContext.put("master_entity", basicEntity2);
		}
		log.info("=======================mater_account:" + count);
		ViewContext.put("mater_account", count);
		return HtmlRestResult.html("/loanManagement/loan_account");
	}

	/**
	 * 修改详情页面
	 * 
	 * @param loanapplyNo
	 * @param massege
	 * @return
	 */
	@RequestMapping(value = "/edit_loan")
	public HtmlRestResult loanfile(String loanapplyNo, String massege) {
		O2oLoanapplyEntity o2oLoanapplyEntity = o2oLoanapplyService.findById(loanapplyNo);
		List<O2oDataListEntity> o2oDataList = o2oDataListService.findByEntityList(loanapplyNo);
		/*
		 * QueryCustomerVO vo = new QueryCustomerVO();
		 * vo.setCustomer_id(o2oLoanapplyEntity.getLoanId()); CustomerView
		 * customer = iCustomerInfoService.geCustomerView(vo);
		 * ViewContext.put("basic", customer.getBasicInfo());
		 * ViewContext.put("expan", customer.getExpansionInfo()); if (customer
		 * != null && customer.getBasicInfo() != null &&
		 * customer.getBasicInfo().getMateId() != null) { QueryCustomerVO vo2 =
		 * new QueryCustomerVO();
		 * vo2.setCustomer_id(customer.getBasicInfo().getMateId()); CustomerView
		 * customer1 = iCustomerInfoService.geCustomerView(vo2);
		 * ViewContext.put("materBasic", customer1.getBasicInfo());
		 * ViewContext.put("materExpan", customer1.getExpansionInfo()); }
		 */
		if ((StatusContexts.LOAN_TYPE_BP.equals(o2oLoanapplyEntity.getLoanType())
				|| StatusContexts.LOAN_TYPE_BP_JX.equals(o2oLoanapplyEntity.getLoanType())
				|| StatusContexts.LOAN_TYPE_SG.equals(o2oLoanapplyEntity.getLoanType())
				|| StatusContexts.LOAN_TYPE_YC.equals(o2oLoanapplyEntity.getLoanType())
				|| StatusContexts.LOAN_TYPE_SC.equals(o2oLoanapplyEntity.getLoanType()))
				&& !StringUtil.isEmpty(o2oLoanapplyEntity.getPartnerId())) {
			String partnerName = partnerService.getPartnerBrandName(o2oLoanapplyEntity.getPartnerId());
			ViewContext.put("partnerName", partnerName);
		}
		List<ActOrgEntity> data = new ArrayList<>();
		ModelResult<List<ActOrgEntity>> da = sysOrgService.getProvinceWithUser(UserHolder.getUser().getNo());
		data = da.getModel();
		ViewContext.put("ActOrgEntitys", data);
		ViewContext.put("o2oDataList", o2oDataList);
		ViewContext.put("errorMassege", massege);

		ViewContext.put("customerId", o2oLoanapplyEntity.getLoanId());
		// 显示之前做封装
		// o2oLoanapplyEntity.getCustomerNo()+o2oLoanapplyEntity.getCustomerCode()+o2oLoanapplyEntity.getCustomeRname();

		ViewContext.put("loanApplyFileEntity", o2oLoanapplyEntity);
		return HtmlRestResult.popHtmlFragment("loanManagement/edit_loaninfo");
	}

	/**
	 * @description 中行推荐函下载
	 */
	@RequestMapping(value = "/downloadRecommendationDoc", method = RequestMethod.GET)
	public void downloadRecommendationDoc(HttpServletResponse httpServletResponse, HttpServletRequest request,
			String referId) {
		OutputStream os = null;
		try {
			O2oLoanapplyEntity loanapplyEntity = o2oLoanapplyService.findById(referId);
			O2oLoanUserEntity loanUserEntity = loanService.findById(loanapplyEntity.getLoanId(), referId);
			Map<String, String> map = new HashMap<String, String>();
			map.put("${name}", loanUserEntity.getUserFullName());
			map.put("${idCord}", loanUserEntity.getDocumentNo());
			NumberFormat nf = new DecimalFormat(",###.00");
			map.put("${loanMoney}", nf.format(loanapplyEntity.getLoanaMount()));
			map.put("${loanTerm}", loanapplyEntity.getLoanTerm() + "个月");
			String templateUrl = "/wordTemplate/recommendation.doc";
			URL base = O2oLoanUserRestController.class.getResource(templateUrl);
			String fileUrl = base.getFile();
			ByteArrayOutputStream document = WordPOIUntil.replaceDoc(fileUrl, map);
			String outfile = "中行推荐函(201512版).doc";
			if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
				outfile = URLEncoder.encode(outfile, "UTF-8");
			} else {
				outfile = new String(outfile.getBytes("UTF-8"), "ISO8859-1");
			}
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setContentType("application/msword");
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			os.write(document.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
	}

	@RequestMapping(value = "/recommendationDoc", method = RequestMethod.GET)
	public HtmlRestResult recommendationDoc(String loanNo) {
		BCRecommendationEntity bcRecommendation = new BCRecommendationEntity();
		if (StringUtil.isNotBlank(loanNo)) {
			ModelResult<BCRecommendationEntity> modelResult = bcRecommendationService
					.queryBCRecommendationByLoanNo(loanNo);
			if (modelResult.getModel() != null) {
				bcRecommendation = modelResult.getModel();
			} else {
				BigDecimal loanMoney = new BigDecimal("10000");
				BigDecimal zero = new BigDecimal("0");
				O2oLoanapplyEntity loanapplyEntity = o2oLoanapplyService.findById(loanNo);
				O2oLoanUserEntity loanUserEntity = loanService.findById(loanapplyEntity.getLoanId(), loanNo);
				bcRecommendation.setCustomerName(loanUserEntity.getUserFullName());
				bcRecommendation.setIDcardNo(loanUserEntity.getDocumentNo());
				bcRecommendation.setLoanTerm(loanapplyEntity.getLoanTerm());
				bcRecommendation.setSuggestTerm(loanapplyEntity.getLoanTerm());
				bcRecommendation.setApproveTerm(loanapplyEntity.getLoanTerm());
				BigDecimal eaMount = loanapplyEntity.getEaMount() == null ? zero : loanapplyEntity.getEaMount();
				eaMount = eaMount.divide(loanMoney, 2, BigDecimal.ROUND_HALF_UP);
				bcRecommendation.setLoanMoney(eaMount);
				bcRecommendation.setSuggestMoney(eaMount);
				bcRecommendation.setApproveMoney(eaMount);
				bcRecommendation.setLoanUse("经营周转");
				// int
				// loanCount=o2oLoanapplyService.findLoanAccountNEW(loanUserEntity.getDocumentNo());
				// bcRecommendation.setLoanCount(loanCount);
				BigDecimal customerSalesamount = loanapplyEntity.getCustomerSalesamount() == null ? zero
						: loanapplyEntity.getCustomerSalesamount();
				bcRecommendation.setAnnualIncome(customerSalesamount.divide(loanMoney, 2, BigDecimal.ROUND_HALF_UP));
				O2oSDEntity sdEntity = o2oSdService.getById(loanNo);
				BigDecimal takeAvgAmount = sdEntity.getTakeAvgAmount() == null ? zero : sdEntity.getTakeAvgAmount();
				bcRecommendation.setEascsAvgOrderMoney(takeAvgAmount.divide(loanMoney, 2, BigDecimal.ROUND_HALF_UP));
				QueryCustomerVO queryCustomerVO = new QueryCustomerVO();
				queryCustomerVO.setCustomer_id(loanUserEntity.getLoanId());
				queryCustomerVO.setShoptype("MAN");
				CustomerShopInfoEntity customerShopInfoEntity = iCustomerInfoService
						.getCustomerShopInfoEntity(queryCustomerVO);
				BigDecimal monthamount1 = customerShopInfoEntity.getMonthamount1() == null ? zero
						: customerShopInfoEntity.getMonthamount1();
				BigDecimal monthamount2 = customerShopInfoEntity.getMonthamount2() == null ? zero
						: customerShopInfoEntity.getMonthamount2();
				BigDecimal monthamount3 = customerShopInfoEntity.getMonthamount3() == null ? zero
						: customerShopInfoEntity.getMonthamount3();
				BigDecimal avgOrderMoney = monthamount1.add(monthamount2).add(monthamount3);
				bcRecommendation.setAvgOrderMoney(avgOrderMoney.divide(loanMoney, 2, BigDecimal.ROUND_HALF_UP));
				bcRecommendation.setEascsCooperationTerm(2);
			}
		}
		bcRecommendation.setLoanAppyNo(loanNo);
		ViewContext.put("BCRecommendation", bcRecommendation);
		return HtmlRestResult.popHtmlFragment("bank/recommendation");
	}

	@RequestMapping(value = "/saveRecommendationDoc", method = RequestMethod.GET)
	public BaseRestResult<String> saveRecommendationDoc(BCRecommendationEntity recommendationEntity,
			String operateIndustryDes) {
		String loanAppyNo = recommendationEntity.getLoanAppyNo();
		Date now = new Date();
		if (StringUtil.isNotBlank(loanAppyNo)) {
			ModelResult<BCRecommendationEntity> modelResult = bcRecommendationService
					.queryBCRecommendationByLoanNo(loanAppyNo);
			ModelResult<Integer> updateMR = null;
			User user = UserHolder.getUser();
			recommendationEntity.setUpdateTime(now);
			recommendationEntity.setUpdator(user.getAccount());
			if (recommendationEntity.getOperateIndustry().equals("其它")) {
				recommendationEntity.setOperateIndustry("其它:" + operateIndustryDes);
			}
			if (modelResult.getModel() != null) {
				updateMR = bcRecommendationService.updateBCRecommendation(recommendationEntity);
			} else {
				recommendationEntity.setCreator(user.getAccount());
				recommendationEntity.setCreateTime(now);
				updateMR = bcRecommendationService.insertBCRecommendation(recommendationEntity);
			}
			if (updateMR.getModel() != null && updateMR.getModel() > 0) {
				BCRecommendationUpdateRecord updateRecord = new BCRecommendationUpdateRecord();
				String json = JSON.toJSONString(recommendationEntity);
				updateRecord.setUpdateContent(json);
				updateRecord.setUpdateTime(now);
				updateRecord.setUpdator(user.getAccount());
				updateRecord.setLoanAppyNo(recommendationEntity.getLoanAppyNo());
				updateRecord.setRecommendationNo(recommendationEntity.getId());
				bcRecommendationService.insertBCRecommendationRecord(updateRecord);
				return BaseRestResult.warn("保存成功").andCloseActionDialog();
			}
		}
		return BaseRestResult.warn("保存失败");
	}

	/**
	 * 增加担保人
	 * 
	 * @param id为o2o_loan_user
	 *            表中的唯一编码
	 * @param massege
	 * @return
	 */
	@RequestMapping(value = "/add_findsponsorfile")
	public HtmlRestResult addSponsorfile(String id) {
		O2oLoanUserEntity sponsor = o2oLoanUserService.queryById(id);
		O2oLoanapplyEntity o2oLoanapplyEntity = o2oLoanapplyService.findById(sponsor.getLoanappNo());
		/**** 查询附件 ****/
		List<O2oDataListEntity> o2oDataList = o2oDataListService.findByEntityList(sponsor.getLoanappNo());
		// QueryCustomerVO vo = new QueryCustomerVO();
		// vo.setCustomer_id(sponsor.getLoanId());
		// CustomerView customer = iCustomerInfoService.geCustomerView(vo);
		O2oLoanUserEntity customer = o2oLoanUserService.findById(sponsor.getLoanId(),
				o2oLoanapplyEntity.getLoanapplyNo());
		// O2oLoanUserEntity customerMate =
		// o2oLoanUserService.findSpouseId(o2oLoanapplyEntity.getLoanId(),o2oLoanapplyEntity.getLoanapplyNo());
		// /add_findsponsorfile
		ViewContext.put("basic", customer);
		ViewContext.put("o2oDataList", o2oDataList);
		ViewContext.put("loanApplyFileEntity", o2oLoanapplyEntity);
		return HtmlRestResult.popHtmlFragment("loanManagement/sponsorfile");
	}

	@SuppressWarnings("static-access")
	@RequestMapping(value = "/save_sponsor")
	public BaseRestResult<String> saveSponsor(String loanapplyNo, String zxid,
			@RequestParam(required = false) String relationshipBorrower) {
		if (StringUtil.isBlank(zxid)) {
			return BaseRestResult.warn("请选择客户。");
		}
		if (StringUtil.isBlank(loanapplyNo)) {
			return BaseRestResult.warn("担保人对应的贷款单号不能为空。");
		}
		O2oZxEntity o2ozxentity = o2oZxServiceImpl.getEntityById(zxid);

		if (o2ozxentity == null) {
			return BaseRestResult.warn("担保人对应的征信单不存在。");
		}
		O2oLoanapplyEntity o2oLoanapplyEntity = o2oLoanapplyService.findById(loanapplyNo);
		if (o2oLoanapplyEntity == null) {
			return BaseRestResult.warn("担保人对应的贷款单不存在。");
		}
		O2oLoanUserEntityZx zxuser = o2oLoadUserZxServiceImpl.getEntityByZxNo(o2ozxentity.getId());
		// 判断这个单是否已经有这个担保人
		O2oLoanUserEntity isexist = o2oLoanUserService.findSponsorById(zxuser.getLoanId(), loanapplyNo);
		if (isexist != null) {
			return BaseRestResult.warn("担保人已存在请勿重复添加。");
		}

		// 校验担保人联系电话是否相同
		Boolean isPhoneEqu = o2oLoanUserService.getDBRCheckUserPhone(loanapplyNo,zxuser.getUserPhone());
			if (isPhoneEqu) {
				return BaseRestResult.warn("所添加的担保人联系电话与已添加担保人、借款人、配偶 不能一致");
			}
		
		// 获取用户的信息
		// CustomerEntity customer =
		// customerService.queryCustomerEntityByCustomerId(customerId);
		CustomerEntity customer = customerService.queryCustomerEntityByCustomerId(zxuser.getLoanId());

		// O2oLoanUserEntity customer =
		// o2oLoanUserService.findById(o2oLoanapplyEntity.getLoanId(),loanapplyNo);
		// O2oLoanUserEntity customerMate =
		// o2oLoanUserService.findSpouseId(o2oLoanapplyEntity.getLoanId(),loanapplyNo);
		if (customer == null) {
			return BaseRestResult.warn("客户号不存在，请重新输入。");
		}
		// 客户在系统有未结清的品牌贷、终端贷、代偿、接力贷、分期贷，则不能添加，点击【下一步】时提示“该客户有未结清的贷款单，不能做担保人”按钮【确认】

		int count = o2oLoanUserService.getCheckCount(customer.getIdNumber());
		if (count > 0) {
			return BaseRestResult.warn("该客户夫妻双方有未结清(包含流程中的)的贷款单，不能做担保人.");
		}
		// 担保人信息入库
		O2oLoanUserEntity o2oLoanUserEntity = O2oLoanUserTransFormart.customerNewToloanUser(new O2oLoanUserEntity(),
				customer, o2oLoanapplyEntity.getLoanapplyNo());
		o2oLoanUserEntity.setSponsorType(StatusContexts.SPONSOR_TYPE_D); // 用户类型
																			// D
																			// 担保人
		o2oLoanUserEntity.setSponsorPermitCredit(StatusContexts.O2O_NO);// 是否允许拿征信，新增的人都不允许拿征信
		if (StringUtils.isNotBlank(relationshipBorrower)) {
			o2oLoanUserEntity.setRelationshipBorrower(relationshipBorrower);
		}
		o2oLoanUserEntity.setZxNo(o2ozxentity.getId());
		o2oLoanUserEntity.setRelationDate(new Date());
		o2oLoanUserEntity.setRelationId(UserHolder.getUser().getNo());
		o2oLoanUserEntity.setRelationName(UserHolder.getUser().getCname());
		int i = o2oLoanapplyService.saveSponsor(o2oLoanUserEntity);
		ViewContext.put("loanApplyFileEntity", o2oLoanapplyEntity);
		ViewContext.put("basicEntity", customer);
		if (i > 0) {
			// return BaseRestResult.buildCloseActionDialogResult()
			// .andActionAjaxLoad("/loanrest/findsponsorfile?loanapplyNo=" +
			// o2oLoanapplyEntity.getLoanapplyNo()
			// + "&customerId=" + zxuser.getLoanId());
			return BaseRestResult.warn("保存成功").refresh();
		} else {
			return BaseRestResult.warn("保存失败");
		}
	}

	@RequestMapping(value = "/save_sponsor_file")
	public BaseRestResult<String> saveSponsorFile(String loanapplyNo, String customerId,
			@RequestParam(required = false) String relationshipBorrower) {
		return BaseRestResult.info("成功").andCloseActionDialog().andJquerySelectAjaxAction("#o2o_SponsorList");
	}

	@RequestMapping(value = "/toAdd_sponsor")
	public HtmlRestResult toAddSponsor(String loanapplyNo) {
		String crmurl = customerLXUrl;
		ViewContext.put("crmurl", crmurl);
		ViewContext.put("crmaddUrl", crmaddUrl);
		ViewContext.put("loanapplyNo", loanapplyNo);
		return HtmlRestResult.popHtmlFragment("loanManagement/add_sponsor");
	}

	/**
	 * 删除担保人
	 * 
	 * @param loanapplyNo
	 * @param customerId
	 * @return
	 */
	@RequestMapping(value = "/delete_sponsor")
	public BaseRestResult<String> deleteSponsor(String id) {
		if (StringUtil.isBlank(id)) {
			return BaseRestResult.warn("担保人id或贷款单id不能为空");
		}
		O2oLoanUserEntity sponsor = loanService.queryById(id);
		List<O2oDataListEntity> o2oDataList = o2oDataListService.findByEntityList(sponsor.getLoanappNo(),
				sponsor.getLoanId());
		int i = 0;
		try {
			i = loanService.deleteSponsor(sponsor, o2oDataList);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		if (i > 0) {
			return BaseRestResult.warn("删除成功").andRefresh();

		} else {
			return BaseRestResult.warn("删除失败");
		}
	}

	/**
	 * 担保人发起征信
	 * 
	 * @param loanapplyNo
	 * @param customerId
	 * @return
	 */
	@RequestMapping(value = "/start_sponsor_credit")
	public BaseRestResult<String> startSponsorCredit(String id) {
		if (StringUtil.isBlank(id)) {
			return BaseRestResult.warn("担保人id或贷款单id不能为空");
		}
		O2oLoanUserEntity sponsor = loanService.queryById(id);
		sponsor.setSponsorPermitCredit(StatusContexts.O2O_YES);
		int i = 0;
		try {
			i = loanService.startSponsorCredit(sponsor);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		if (i > 0) {
			return BaseRestResult.warn("发起征信成功").andRefresh();

		} else {
			return BaseRestResult.warn("发起征信删除失败");
		}
	}

	/**
	 * 担保人上传附件
	 * 
	 * @param loanapplyNo
	 * @param customerId
	 * @return
	 */
	@RequestMapping(value = "/findsponsorfile")
	public HtmlRestResult sponsorfile(String loanapplyNo, String customerId) {
		O2oLoanapplyEntity o2oLoanapplyEntity = o2oLoanapplyService.findById(loanapplyNo);
		/**** 查询附件 ****/
		List<O2oDataListEntity> o2oDataList = o2oDataListService.findByEntityList(loanapplyNo);
		/*
		 * QueryCustomerVO vo = new QueryCustomerVO();
		 * vo.setCustomer_id(customerId); CustomerView customer =
		 * iCustomerInfoService.geCustomerView(vo);
		 */

		O2oLoanUserEntity o2oSponsor = o2oLoanUserService.findSponsorById(customerId, loanapplyNo);
		ViewContext.put("basic", o2oSponsor);
		ViewContext.put("o2oDataList", o2oDataList);
		ViewContext.put("loanApplyFileEntity", o2oLoanapplyEntity);
		return HtmlRestResult.popHtmlFragment("loanManagement/sponsorfile");
	}

	/**
	 * @Description:
	 * 				<p>
	 *               显示担保人详细信息
	 *               </p>
	 * @author yy
	 * @date 2016年12月5日
	 * @version V1.0
	 * @param billCode,loanapplyNo
	 * @return BaseRestResult<String>
	 */
	@RequestMapping("/sponsorDetail")
	public PaginationRestResult sponsorDetail(LoanUserForm loanUserForm, String flag, String approvalStatus) {
		// 获取担保人列表
		PageResult<Object[]> pageResult = o2oLoanUserService.findSponsor(loanUserForm);
		/*
		 * String[] oatitles = { "姓名", "身份证号", "联系电话", "征信状态","是否已经发起征信",
		 * "担保人身份证附件", "担保人手持授权书及身份证照片", "担保人征信业务授权书", "担保人征信报告", "征信报告更新时间" };
		 */
		String[] oatitles = { "姓名", "与借款人关系", "银行征信报告", "第三方征信报告", "更新时间", "更新人" };
		Button[] titleButtons = new Button[] {

				ButtonHelper.createAjaxButton(null,
						"/sponsorInfo/rest/sponsor_detail?sponsorId={3}" + "&loanapplyNo="
								+ loanUserForm.getLoanapplyNo() + "&flag=" + flag + "&approvalStatus=" + approvalStatus),
				null, ButtonHelper.createOpenButton(null, "/file/download?datalistno={0}"),
				ButtonHelper.createOpenButton(null, "/file/download?datalistno={1}"), null, null };
		// Button shenqign = ButtonHelper.createAjaxButton("同意征信",
		// "/loanrest/start_sponsor_credit?id={4}");
		// shenqign.setShowButtonFilter(showBottun);
		// shenqign.setPermissionCode("sponsorCredit"); // 权限按钮
		// 上传征信材料按钮
		// Button sponsorUplod = ButtonHelper.createAjaxButton("上传征信材料",
		// "/loanrest/add_findsponsorfile?id={4}");
		// sponsorUplod.setShowButtonFilter(showBottunf);
		// sponsorUplod.setPermissionCode("sponsorUploadFile"); // 权限按钮
		// 删除按钮
		Button deleteSponsor = ButtonHelper.createAjaxConfirmButton("删除", "/loanrest/delete_sponsor?id={2}");
		deleteSponsor.setShowButtonFilter(deleteBottunf);
		deleteSponsor.setPermissionCode("sponsorDeleteCode"); // 权限按钮
		O2oLoanapplyEntity loanapplyEntity = o2oLoanapplyService.findById(loanUserForm.getLoanapplyNo());
		Button[] findButton = new Button[] {};
		if ("NF".equals(loanapplyEntity.getWfType()) || "S".equals(loanapplyEntity.getWfType())
				|| "O".equals(loanapplyEntity.getWfType()) || "HN".equals(loanapplyEntity.getWfType())) {
			if ("BC".equals(loanapplyEntity.getBankLoanName())) {
				Button dbButtom = new Button("担保人打印",
						"/downloadDbrPdf?customer_id={3}&loanapplyNo=" + loanUserForm.getLoanapplyNo());
				dbButtom.setPermissionCode("dbrPrint"); // 权限按钮shenqign,
														// sponsorUplod,
				findButton = new Button[] { deleteSponsor, dbButtom };

			} else {
				findButton = new Button[] { deleteSponsor };
			}
		} else {
			findButton = new Button[] { deleteSponsor };
		}

		PaginationInfo datalistInfo = new PaginationInfo(pageResult, oatitles);
		datalistInfo.setMoreButtons(findButton);
		datalistInfo.setTitleButtons(titleButtons);
		datalistInfo.setBuildPagingNavigation(false);
		datalistInfo.setFirstRenderColumnIndex(4);
		datalistInfo.setBuildRowNumber(true);
		return PaginationRestResult.buildPaginationRestResult(datalistInfo);
	}

	/**
	 * @Description:
	 * 				<p>
	 *               显示担保人个人征信信息
	 *               </p>
	 * @author LMX
	 * @date 2017年9月11日 上午10:40:36
	 * @version V1.0
	 * @param loanUserForm
	 * @return
	 */
	@RequestMapping("/sponsorPersonalDetail")
	public PaginationRestResult sponsorPersonalDetail(LoanUserForm loanUserForm) {
		// 获取担保人列表
		PageResult<Object[]> pageResult = o2oLoanUserService.findSponsorPersonal(loanUserForm);

		String[] oatitles = { "姓名", "与借款人关系", "银行征信报告", "银行征信报告时间", "第三方征信报告", "第三方征信报告时间", "更新时间", "更新人" };
		Button[] titleButtons = new Button[] {
				// ButtonHelper.createAjaxButton(null,
				// "/sponsorInfo/rest/sponsor_detail?sponsorId={3}"+"&loanapplyNo="+loanUserForm.getLoanapplyNo()),
				null, null, ButtonHelper.createOpenButton(null, "/file/download?datalistno={0}"), null,
				ButtonHelper.createOpenButton(null, "/file/download?datalistno={1}"), null, null, null };

		// 删除按钮
		Button deleteSponsor = ButtonHelper.createAjaxConfirmButton("删除", "/loanrest/delete_sponsor?id={2}");
		deleteSponsor.setShowButtonFilter(deleteBottunf);
		deleteSponsor.setPermissionCode("sponsorDeleteCode"); // 权限按钮
		O2oLoanapplyEntity loanapplyEntity = o2oLoanapplyService.findById(loanUserForm.getLoanapplyNo());
		Button[] findButton = new Button[] {};
		if ("NF".equals(loanapplyEntity.getWfType()) || "S".equals(loanapplyEntity.getWfType())
				|| "O".equals(loanapplyEntity.getWfType()) || "HN".equals(loanapplyEntity.getWfType())) {
			if ("BC".equals(loanapplyEntity.getBankLoanName())) {
				Button dbButtom = new Button("担保人打印",
						"/downloadDbrPdf?customer_id={3}&loanapplyNo=" + loanUserForm.getLoanapplyNo());
				dbButtom.setPermissionCode("dbrPrint"); // 权限按钮shenqign,
														// sponsorUplod,
				findButton = new Button[] { deleteSponsor, dbButtom };

			} else {
				findButton = new Button[] { deleteSponsor };
			}
		} else {
			findButton = new Button[] { deleteSponsor };
		}

		PaginationInfo datalistInfo = new PaginationInfo(pageResult, oatitles);
		datalistInfo.setMoreButtons(findButton);
		datalistInfo.setTitleButtons(titleButtons);
		datalistInfo.setBuildPagingNavigation(false);
		datalistInfo.setFirstRenderColumnIndex(4);
		datalistInfo.setBuildRowNumber(true);
		return PaginationRestResult.buildPaginationRestResult(datalistInfo);
	}

	/**
	 * @Description:
	 * 				<p>
	 *               显示夫妻双方担保贷款信息
	 *               </p>
	 * @author yy
	 * @date 2016年12月5日
	 * @version V1.0
	 * @param billCode,loanapplyNo
	 * @return BaseRestResult<String>
	 */
	@RequestMapping("/sponsorLoanapply")
	public PaginationRestResult sponsorLoanapply(LoanUserForm loanUserForm, String flag) {

		// 根据用户id找配偶id
		// if(loanUserForm.getUserId()!=null&&loanUserForm.getLoanapplyNo()!=null){
		// QueryCustomerVO vo = new QueryCustomerVO();
		// vo.setCustomer_id(loanUserForm.getUserId());
		// //CustomerView customer = iCustomerInfoService.geCustomerView(vo);
		// //CustomerBasicInfoEntity basicEntity = customer.getBasicInfo();
		// O2oLoanUserEntity o2oLoanUserEntity=
		// o2oLoanUserService.findSpouseId(loanUserForm.getUserId(),loanUserForm.getLoanapplyNo());
		// // 不取crm那边的配偶id，取本地申请的时候存的
		// //if(basicEntity.getMateId()!=null){//配偶id
		// if(o2oLoanUserEntity.getLoanId()!=null){//配偶id
		// String userIds =
		// loanUserForm.getUserId()+","+o2oLoanUserEntity.getLoanId();
		// loanUserForm.setUserId(userIds);
		// }else{
		// loanUserForm.setUserId("'"+loanUserForm.getUserId()+"'");
		// }
		// }else{
		// BaseRestResult.warn("客户id不能为空");
		// }

		if (loanUserForm.getUserId() != null) {

			CustomerEntity customer = customerService.queryCustomerEntityByCustomerId(loanUserForm.getUserId());
			if (customer != null) {
				if (customer.getMateId() != null) {// 配偶id
					String userIds = "'" + loanUserForm.getUserId() + "','" + customer.getMateId() + "'";
					loanUserForm.setUserId(userIds);
				} else {
					loanUserForm.setUserId("'" + loanUserForm.getUserId() + "'");
				}
			} else {
				log.error("客户id为" + loanUserForm.getUserId() + ":在crm中未找到该客户");
			}

		} else {
			log.error("客户id不能为空");
			// BaseRestResult.warn("客户id不能为空");
		}
		// 获取担保贷款列表
		PageResult<Object[]> pageResult = o2oLoanUserService.findSponsorLoanapply(loanUserForm);
		String[] oatitles = { "贷款单号", "担保人", "借款人姓名", "经办平台", "放款银行", "申请金额", "放款金额", "申请状态", "放款日期", "到期日期" };
		SelectDataOption[] selectDataOptions = { null, null, null, null, new SelectDataOption("BANKTYPEO2O"), null,
				null, new SelectDataOption("SQZT"), null, null };
		PaginationInfo datalistInfo = new PaginationInfo(pageResult, oatitles);
		if (!StringUtils.isEmpty(flag)) {
			Button[] titleButtons = new Button[] {
					ButtonHelper.createOpenButton(null, serviceHomeUrl + "/detail?loanapplyNo={0}"), null, null, null,
					null, null, null, null, null };
			datalistInfo.setTitleButtons(titleButtons);
		}
		datalistInfo.setBuildPagingNavigation(false);
		datalistInfo.setFirstRenderColumnIndex(1);
		datalistInfo.setBuildRowNumber(true);
		datalistInfo.setSelectDataOptions(selectDataOptions);
		return PaginationRestResult.buildPaginationRestResult(datalistInfo);
	}

	/**
	 * 担保人上传附件
	 * 
	 * @param loanapplyNo
	 * @param customerId
	 * @return
	 */
	@RequestMapping("/loan_detail")
	public HtmlRestResult sponsorDetail1(LoanUserForm loanUserForm) {
		PageResult<Object[]> pageResult = o2oLoanUserService.findSponsor(loanUserForm);
		List<Object[]> sponsorList = pageResult.getData();
		ViewContext.put("sponsorList", sponsorList);
		return HtmlRestResult.popHtmlFragment("loanManagement/sponsorlist");
	}

	/**
	 * 是否显示发起征信查询按钮
	 */
	public ShowButtonFilter showBottun = new ShowButtonFilter() {
		@Override
		public boolean filter(Object param) {
			Object[] params = (Object[]) param;
			if (params[0] != null && params[1] != null && params[2] != null && "N".equals(params[9])
					&& params[3] == null) { // 担保人的三种附件都上传完成之后才显示发起征信按钮,并且没有发起征信的，并且没有征信报告
				return true;
			} else {
				return false;
			}
		}
	};

	/**
	 * 是否显示上传征信附件按钮
	 */
	public ShowButtonFilter showBottunf = new ShowButtonFilter() {
		@Override
		public boolean filter(Object param) {
			Object[] params = (Object[]) param;
			if (params[3] == null) {
				return true;
			} else {
				return false;
			}
		}
	};

	/**
	 * 是否显示担保人删除按钮
	 */
	public ShowButtonFilter deleteBottunf = new ShowButtonFilter() {
		@Override
		public boolean filter(Object param) {
			Object[] params = (Object[]) param;
			// 获取贷款单号
			O2oLoanUserEntity sponsor = loanService.queryById((String) params[2]);
			if (sponsor != null) {
				O2oLoanapplyEntity o2oLoanapplyEntity = o2oLoanapplyService.findById(sponsor.getLoanappNo());
				String type = o2oLoanapplyEntity.getWfType();
				if (StatusContexts.O2O_NEW.equals(type) || StatusContexts.O2O_ZX_BEGIN.equals(type)
						|| StatusContexts.O2O_ZX_END.equals(type) || StatusContexts.O2O_NS_BEGIN.equals(type)
						|| StatusContexts.O2O_NS_END.equals(type)) {
					return true;
				} else {
					return false;
				}
			} else {
				return false;
			}
		}
	};

	/**
	 * @Description:
	 * 				<p>
	 *               插入文件修改日志
	 *               </p>
	 * @author CXW
	 * @date 2016年9月26日 下午2:35:13
	 * @version V1.0
	 * @param logType
	 *            日志类型,updateStr 修改内容
	 * @return void
	 */
	public void insertLog(String logType, String updateStr) {
		try {
			o2oLoanapplyService.saveLog(UserHolder.getUser().getCname(), logType, null, updateStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @Description:
	 * 				<p>
	 *               脱敏查看弹窗
	 *               </p>
	 * @author LMX
	 */
	@RequestMapping(value = "/user_sensitive")
	public HtmlRestResult userSensitive(String loanapplyNo) {
		O2oLoanapplyEntity loanapply = o2oLoanapplyService.findById(loanapplyNo);
		QueryCustomerVO vo = new QueryCustomerVO();
		vo.setCustomer_id(loanapply.getLoanId());
		CustomerView customer = iCustomerInfoService.geCustomerView(vo);
		O2oLoanUserEntity loanUser = o2oLoanapplyService.findLoanUserEntity(loanapply.getLoanapplyNo(),
				loanapply.getLoanId());
		CustomerBasicInfo customerBasicInfo = o2oLoanapplyService.getCustomerEntityById(loanUser.getId());
		ViewContext.put("loanUser", loanUser);
		ViewContext.put("basic", customerBasicInfo);
		ViewContext.put("expan", customer.getExpansionInfo());
		ViewContext.put("loanapply", loanapply);
		String crmurl = customerLXUrl;
		ViewContext.put("crmurl", crmurl);
		ViewContext.put("crmaddUrl", crmaddUrl);
		ViewContext.put("loanapplyNo", loanapplyNo);
		// 配偶信息
		O2oLoanUserEntity materEntity = o2oLoanUserService.findSpouseId(loanapply.getLoanId(), loanapplyNo);
		if (materEntity != null) {
			QueryCustomerVO vo2 = new QueryCustomerVO();
			vo2.setCustomer_id(materEntity.getLoanId());
			CustomerView customer1 = iCustomerInfoService.geCustomerView(vo2);
			ViewContext.put("materBasic", customer1.getBasicInfo());
		} else {
			ViewContext.put("materBasic", new CustomerView());
		}

		return HtmlRestResult.popHtmlFragment("loanManagement/user_sensitive");
	}

	/**
	 * CXW 贷款详情显示证件号码等信息星号 http://tick.o2ojr.eascs.com/ticket/view/loan-12592
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/show_window")
	public BaseRestResult<String> show_window(String id) {
		O2oLoanUserEntity loanUserEntity = o2oLoanUserService.queryById(id);
		CustomerBasicInfo customerBasicInfo = o2oLoanapplyService.getCustomerEntityById(loanUserEntity.getId());
		ViewContext.put("vo", loanUserEntity);
		ViewContext.put("basic", customerBasicInfo);
		return HtmlRestResult.popHtmlFragment("/detail/loanuser_show_info");
	}
	
	/**
	 * @Description:
	 *               <p>
	 *               借款人和配偶的证件号码(身份证号)documentNo脱敏
	 *               </p>
	 * @author LMX
	 * @date 2018年1月4日 下午1:37:35
	 */
	@RequestMapping("/show_documentNo")
	public BaseRestResult<String> show_documentNo(String id) {
		O2oLoanUserEntity loanUserEntity = o2oLoanUserService.queryById(id);
		CustomerBasicInfo customerBasicInfo = o2oLoanapplyService.getCustomerEntityById(loanUserEntity.getId());
		ViewContext.put("vo", loanUserEntity);
		ViewContext.put("basic", customerBasicInfo);
		return HtmlRestResult.popHtmlFragment("/detail/documentNo_show_info");
	}

	@RequestMapping("/show_spouse")
	public BaseRestResult<String> show_spouse(String id) {
		O2oLoanUserEntity loanUserEntity = o2oLoanUserService.queryById(id);
		CustomerBasicInfo customerBasicInfo = o2oLoanapplyService.getCustomerEntityById(loanUserEntity.getId());
		ViewContext.put("vo", loanUserEntity);
		ViewContext.put("basic", customerBasicInfo);
		return HtmlRestResult.popHtmlFragment("/detail/loanSpouse_show_info");
	}

	@RequestMapping(value = "/third_party_view")
	public BaseRestResult<String> third_party_view(String loanapplyNo, String readonly) {
		ViewContext.put("loanapplyNo", loanapplyNo);
		ViewContext.put("readonly", readonly);
		return new HtmlRestResult("o2ozx/third_party");
	}

	@RequestMapping(value = "/third_party")
	public BaseRestResult<String> third_party(String loanapplyNo, String readonly) {
		String titles[] = { "报告类型", "报告名称", "报告来源" };
		List<Object[]> data = new ArrayList<Object[]>();
		log.info("访问第三方征信报告处，贷款id：【{}】，是否可以查看：【{}】", loanapplyNo, readonly);
		List<O2oLoanUserEntity> queryUsersByLoanapplyNo = loanService.queryUsersByLoanapplyNo(loanapplyNo);
		User user = UserHolder.getUser();
		Button[] titleButtons = new Button[] { null, ButtonHelper.createOpenButton(null,
				crmUrl + "/td/getPreloanReport?name={3}&idCard={4}&phone={5}&loanId={6}") };
		for (O2oLoanUserEntity loanUserEntity : queryUsersByLoanapplyNo) {
			log.info(
					"第三方征信报告参数检查,loanapplyNo:{},loanapplyEntity.getLoanId:{},user.getAccount:{},name:{},idCard:{},phone:{}",
					loanapplyNo, loanUserEntity.getLoanId(), user.getAccount(), loanUserEntity.getUserFullName(),
					loanUserEntity.getDocumentNo(), loanUserEntity.getUserPhone());
			String type = "";
			if (StringUtil.isBlank(loanUserEntity.getSpouseId()) && "D".equals(loanUserEntity.getSponsorType())) {
				type = "担保人";
			} else if (StringUtil.isNotBlank(loanUserEntity.getSpouseId())) {
				type = "配偶";
			} else {
				type = "借款人";
			}
			String name = AESUtil.encrypt(loanUserEntity.getUserFullName(), user.getAccount());
			String idCard = AESUtil.encrypt(loanUserEntity.getDocumentNo(), user.getAccount());
			String phone = AESUtil.encrypt(loanUserEntity.getUserPhone(), user.getAccount());
			phone = AESUtil.encrypt(loanUserEntity.getUserPhone(), user.getAccount());
			try {
				name = URLEncoder.encode(name, "utf-8");
				idCard = URLEncoder.encode(idCard, "utf-8");
				phone = URLEncoder.encode(phone, "utf-8");
			} catch (UnsupportedEncodingException e) {
				log.error("转码报错：{}", e.getMessage());
				;
			}
			Object[] datas = { type, loanUserEntity.getUserFullName() + "的征信报告", "同盾", name, idCard, phone, phone };
			data.add(datas);
		}

		PageResult<Object[]> pageResult = new PageResult<Object[]>();
		pageResult.setData(data);

		PaginationInfo datalistInfo = new PaginationInfo(pageResult, titles);
		if ("false".equals(readonly)) {
			datalistInfo.setTitleButtons(titleButtons);
		}
		datalistInfo.setBuildPagingNavigation(false);
		datalistInfo.setFirstRenderColumnIndex(0);
		datalistInfo.setBuildRowNumber(true);
		datalistInfo.setRendTo("#o2o_third_party");
		ViewContext.put("paginationInfo", datalistInfo);

		return new HtmlRestResult("o2ozx/td_jm");

	}
}
